package com.ruihang.generalibrary.utils;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.jiongbull.jlog.JLog;

import retrofit2.http.PUT;

/**
 * Created by liuyu on 2017/9/14.
 */

public class GeneraLifeObser {

    public static final int STATE_ATTACH = 1;
    public static final int STATE_CREATED = 2;
    public static final int STATE_CREATED_V = 3;
    public static final int STATE_START = 4;
    public static final int STATE_RESUME = 5;
    public static final int STATE_PAUSE = 6;
    public static final int STATE_STOP = 7;
    public static final int STATE_DESTORY_V = 8;
    public static final int STATE_DESTORY = 9;
    public static final int STATE_DETACH = 10;

    private static GeneraLifeObser instance;

    private ArrayMap<String, Integer> lifeStates;

    private GeneraLifeObser() {
        lifeStates = new ArrayMap<>();
    }

    public void changeLifeState(String name, int state) {
        lifeStates.put(name, state);
    }

    public Integer getLifeStates(String name) {
        return lifeStates.get(name);
    }

    public void removeLifes(String name) {
        lifeStates.remove(name);
    }

    public static GeneraLifeObser getInstance() {
        if (instance == null) {
            instance = new GeneraLifeObser();
        }
        return instance;
    }

    public static void changeLifeState(Activity activity, int state) {
        getInstance().changeLifeState(activity + "", state);
    }

    public static void changeLifeState(Fragment fragment, int state) {
        getInstance().changeLifeState(fragment + "", state + 100);
    }

    public static Integer getLifeState(String name) {
        return getInstance().getLifeStates(name);
    }

    public static void removeLife(Fragment fragment) {
        getInstance().removeLifes(fragment + "");
    }

    public static void removeLife(AppCompatActivity activity) {
        getInstance().removeLifes(activity + "");
    }
    public static void removeLife(FragmentActivity activity) {
        getInstance().removeLifes(activity + "");
    }
    public static boolean isOwnerLife(String owner) {
        if (TextUtils.isEmpty(owner)) {
            return false;
        }
        Integer i = getLifeState(owner);
        if (i==null){
            return false;
        }
        if (i > 100) {
            i = i - 100;
            return i >= STATE_ATTACH && i < STATE_DESTORY_V;
        } else {
            return i >= STATE_CREATED && i < STATE_DESTORY;
        }
    }
}
